package com.efounder.addressselector.greendao;

import com.efounder.util.AppContext;

import org.greenrobot.greendao.database.Database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SessionUtil {
    private static DaoSession daoSession;
    public static DaoSession getInstance() {
        try {
            copyDataBase("mall_address.db");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (daoSession == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(AppContext.getInstance(), "mall_address.db");
            Database db = helper.getWritableDb();
            daoSession = new DaoMaster(db).newSession();
        }
        return daoSession;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private static void copyDataBase(String dbname) throws IOException {
        // Path to the just created empty db
        File outFileName = AppContext.getInstance().getDatabasePath(dbname);

        if (!outFileName.exists()) {
            // Open your local db as the input stream
            InputStream myInput = AppContext.getInstance().getAssets().open(dbname);
            outFileName.getParentFile().mkdirs();

            // Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
    }
}
